<?php

namespace app\api\controller;

use app\common\lib\Arr;
use app\common\lib\Show;
use app\common\lib\Time;
use think\response\Json;

class WorkerServer
{

    //case 1 审核中的零活process_status=0，开工时间到自动变为已过期
    //case 2 招工中的零活process_status=1，根据预估工期自动完工（更新状态及完工时间）
    public function sendTimeOutMessage(){
        ini_set('max_execution_time',0);
        ini_set('memory_limit', -1);

        $workBis = new \app\common\business\Work();
        $workModel = new \app\common\model\mysql\Work();

        $condition = [
            ['process_status','in',[0,1]]
        ];
        $workList = $workBis->getListByWhere($condition,0,0,'id,name,process_status,is_show,start_time,end_time,valuation,duration');
        if (!empty($workList)){
            $workListTimeOut = []; //过期
            $workListFinish = []; //完工

            foreach ($workList as $k=>$v){
                $v['process_status'] == 0 && $workListTimeOut[] = $v;
                $v['process_status'] == 1 && $workListFinish[] = $v;
            }
            unset($workList);

            if (!empty($workListTimeOut)){
                $updateTimeOutIds = [];
                foreach ($workListTimeOut as $k=>$v){
                    //当前时间晚于开工时间，记录过期work的id
                    time() >= $v['start_time'] && $updateTimeOutIds[] = $v['id'];
                }

                if (!empty($updateTimeOutIds)){
                    $updateTimeOutData = [
                        'process_status'=>4,
                        'update_time'=>time()
                    ];
                    $workModel->updateByIds($updateTimeOutIds,$updateTimeOutData);
                }
            }

            if (!empty($workListFinish)){
                $updateFinish = [];
                foreach ($workListFinish as $k=>$v){
                    if ($v['valuation'] == 1){
                        //短期工 / 天
                        $duration = $v['duration'] * 24 * 60 * 60;
                        $finish_time = $v['start_time'] + $duration;
                    }elseif($v['valuation'] == 2){
                        //钟点工 / 小时
                        $duration = $v['duration'] * 60 * 60;
                        $finish_time = $v['start_time'] + $duration;
                    }

                    if (in_array($v['valuation'],[1,2])){
                        if(time() >= $finish_time){
                            $updateFinish[] = [
                                'id'=>$v['id'],
                                'process_status'=>2,
                                'finish_time'=>intval($finish_time),
                                'update_time'=>time(),
                            ];
                        }
                    }
                }
                if (!empty($updateFinish)){
                    $workModel->saveAll($updateFinish);
                }
            }
        }

        echo date('Y-m-d H:i:s').'_success;';
    }
}